<template>
  <div class="video-list main-content">
    <div class="screen-box">
      <div class="screen-item">
        <el-input
          v-model="keywords"
          size="small"
          placeholder="输入关键词"
          clearable
          style="width:220px"
          @keyup.enter.native="fetchData"
        />
        <el-select
          v-model="major"
          size="small"
          clearable
          placeholder="请选择专业"
        >
          <el-option
            v-for="item in majorList"
            :key="item._id"
            :label="item.majorName"
            :value="item._id"
          />
        </el-select>
        <el-select
          v-model="teacher"
          size="small"
          clearable
          placeholder="授课教师"
        >
          <el-option
            v-for="item in teacherList"
            :key="item._id"
            :label="item.realName"
            :value="item._id"
          />
        </el-select>
        <el-button size="small" icon="el-icon-search" type="primary" @click.native="fetchData">搜索</el-button>
      </div>
      <div class="operation">
        <el-button
          size="small"
          icon="el-icon-plus"
          type="primary"
          @click="showDialog('add')"
        >新增</el-button>
      </div>
    </div>
    <div class="content">
      <el-table :data="courseList">
        <el-table-column label="课程封面" align="center">
          <template slot-scope="scope">
            <img :src="scope.row.cover" width="50" alt="" class="cover">
          </template>
        </el-table-column>
        <el-table-column prop="courseName" label="课程名称" align="center" />
        <el-table-column label="专业名称" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.major">{{
              scope.row.major.majorName
            }}</span>
            <span v-else>未选择</span>
          </template>
        </el-table-column>
        <el-table-column label="授课教师" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.teacher">{{
              scope.row.teacher.name
            }}</span>
            <span v-else>未选择</span>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开课时间" align="center" />
        <el-table-column prop="endTime" label="结课时间" align="center" />
        <el-table-column prop="selectedNum" label="已选" align="center" />
        <el-table-column prop="availableNum" label="可选人数" align="center" />
        <el-table-column label="课程状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status | statusFilter">{{
              scope.row.status == 1 ? '未开课' : scope.row.status == 2?'开课中': '已结束'
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.createTime | timeFormat }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.updateTime | timeFormat }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template slot-scope="scope">
            <!-- <router-link :to="`episodes/?id=${scope.row._id}`">
              <el-button size="mini">剧集</el-button>
            </router-link> -->
            <el-button
              size="mini"
              type="primary"
              @click.native="showDialog('edit', scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row._id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-box">
        <el-pagination
          :total="total"
          :current-page="currentPage"
          :page-sizes="[5, 10, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 权限新增，详情，编辑弹框 -->
    <el-dialog
      v-dialogDrag
      center
      :title="
        dialogType == 'add'
          ? '新增课程'
          : dialogType == 'edit'
            ? '编辑课程'
            : '课程详情'
      "
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="130px"
        label-position="rigth"
        size="small"
      >
        <el-form-item label="课程封面" prop="cover">
          <img-upload
            :disabled="dialogType == 'detail'"
            :img-data="form.cover"
            :pic-max="1"
            @chooseImg="imageChoose"
          />
          <el-input v-model="form.cover" placeholder="您还可以输入封面url，这将不会录入图库资源" clearable />
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-input
            v-model="form.courseName"
            placeholder="输入课程名称"
            :disabled="dialogType == 'detail'"
          />
        </el-form-item>
        <el-form-item label="专业类别" prop="major">
          <el-select
            v-model="form.major"
            clearable
            placeholder="请选择专业类别"
            :disabled="dialogType == 'detail'"
          >
            <el-option
              v-for="item in majorList"
              :key="item._id"
              :label="item.majorName"
              :value="item._id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="授课教师" prop="teacher">
          <el-select
            v-model="form.teacher"
            clearable
            placeholder="请选择授课教师"
            :disabled="dialogType == 'detail'"
          >
            <el-option
              v-for="item in teacherList"
              :key="item._id"
              :label="item.realName"
              :value="item._id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程时间" prop="courseTime">
          <el-date-picker
            v-model="courseTime"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="可选人数">
          <el-input
            v-model="form.availableNum"
            placeholder="输入可选人数"
            :disabled="dialogType == 'detail'"
          />
        </el-form-item>
        <el-form-item label="课程描述">
          <el-input
            v-model="form.description"
            placeholder="输入课程描述"
            type="textarea"
            :disabled="dialogType == 'detail'"
          />
        </el-form-item>
        <el-form-item label="课程排序">
          <el-input
            v-model="form.sort"
            placeholder="输入课程排序"
            :disabled="dialogType == 'detail'"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            v-if="dialogType !== 'detail'"
            type="primary"
            @click="onSubmit('form')"
          >保存</el-button>
          <el-button
            v-else
            type="primary"
            @click="dialogType = 'edit'"
          >编辑</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { courseApi } from '@/api/course'
import { majorApi } from '@/api/major'
import { adminApi } from '@/api/manage'
import { formatTime } from '@/utils'
import ImgUpload from '@/components/ImgUpload'
export default {
  components: {
    ImgUpload
  },
  filters: {
    timeFormat(time) {
      return formatTime(new Date(time))
    },
    statusFilter(status) {
      const statusMap = {
        1: 'danger',
        2: 'success',
        3: 'warnning'
      }
      return statusMap[status]
    }
  },
  data() {
    var validateCourseTime = (rule, value, callback) => {
      if (this.courseTime === [] || !this.courseTime) {
        callback(new Error('请选择课程时间'))
      } else {
        callback()
      }
    }
    return {
      loading: true,
      keywords: '',
      courseList: [], // 课程列表
      majorList: [], // 专业列表
      teacherList: [], // 教师列表
      dialogFormVisible: false,
      form: {
        courseName: '', // 课程名称
        cover: '', // 课程封面
        major: '', // 所属专业
        teacher: '', // 授课教师
        startTime: '', // 课程开始时间
        endTime: '', // 课程结束时间
        availableNum: '', // 可选人数
        sort: '0', // 排序
        description: '' // 课程描述
      },
      pageSize: 10,
      currentPage: 1,
      total: 0,
      currentMajor: {}, // 详情 当前专业
      major: '', // 筛选专业
      teacher: '', // 筛选教师
      courseTime: [],
      rules: {
        courseName: [{ required: true, trigger: 'blur', message: '请填写课程名称' }],
        major: [{ required: true, trigger: 'change', message: '请选择专业类别' }],
        teacher: [{ required: true, trigger: 'change', message: '请选择授课教师' }],
        courseTime: [{ validator: validateCourseTime, trigger: 'change' }],
        icon: [{ required: true, trigger: 'blur', message: '请上传课程封面' }]
      },
      dialogType: 'add'
    }
  },
  watch: {
    dialogFormVisible(val) {
      if (val === false) {
        this.form = {
          courseName: '', // 课程名称
          cover: '', // 课程封面
          major: '', // 所属专业
          teacher: '', // 授课教师
          startTime: '', // 课程开始时间
          endTime: '', // 课程结束时间
          classTime: [], // 上课时间
          availableNum: '', // 可选人数
          sort: '0', // 排序
          description: '' // 课程描述
        }
        this.courseTime = []
        this.currentMajor = {}
        this.$refs.form.resetFields()
        this.$refs.form.clearValidate()
      }
    },
    courseTime(newVal) {
      if (!newVal) {
        this.form.startTime = ''
        this.form.endTime = ''
      } else {
        this.form.startTime = newVal[0]
        this.form.endTime = newVal[1]
      }
    }
  },
  created() {
    this.fetchData()
  },
  mounted() {
    this.getMajor()
    this.getTeachers()
  },
  methods: {
    fetchData() {
      // 获取管理员列表
      courseApi.getList({
        pageSize: this.pageSize,
        currentPage: this.currentPage,
        keywords: this.keywords,
        major: this.major,
        teacher: this.teacher
      }).then(res => {
        this.courseList = res.data.list
        this.total = res.data.count
      })
    },
    getTeachers() {
      // 获取教师列表
      adminApi.getAdminList({
        pageSize: 1000,
        currentPage: 1,
        roleType: 2
      }).then(res => {
        this.teacherList = res.data.list
      })
    },
    // 获取专业列表
    getMajor() {
      majorApi.getList({
        pageSize: 1000,
        currentPage: 1
      }).then(res => {
        this.majorList = res.data.list
      })
    },
    changeRecommend(row) {
      this.$confirm('是否修改首页推荐?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'danger'
      }).then(() => {
        courseApi.updateItem({
          _id: row._id,
          recommend: row.recommend === '0' ? '1' : '0'
        }).then(res => {
          this.$message.success(res.msg || '修改成功')
          // 重置表单
          this.dialogFormVisible = false
          this.fetchData()
        }).catch(err => {
          this.$message.error(err || '编辑失败!')
        })
      })
    },
    changeMajor(item) {
      // this.form.major = item._id
    },
    changeTeacher(item) {
      // this.form.teacher = item._id
    },
    showDialog(type, form) {
      this.dialogType = type
      this.dialogFormVisible = true
      if (form && form._id) {
        // 请求分类详情
        const { major, teacher } = form
        this.form = { ...form, major: major._id, teacher: teacher._id }
      }
    },
    onSubmit(formName) {
      const _this = this
      _this.$refs[formName].validate(valid => {
        if (valid) {
          if (_this.form._id) {
            courseApi.updateItem(_this.form).then(res => {
              this.$message.success(res.msg)
              // 重置表单
              this.$nextTick(() => {
                _this.$refs[formName].resetFields()
              })
              this.dialogFormVisible = false
              this.fetchData()
            }).catch(err => {
              this.$message.error(err || '编辑失败!')
            })
          } else {
            courseApi.addItem(_this.form).then(res => {
              this.$message.success(res.msg)
              // 重置表单
              this.$nextTick(() => {
                _this.$refs[formName].resetFields()
              })
              this.dialogFormVisible = false
              this.fetchData()
            }).catch(err => {
              this.$message.error(err || '添加失败!')
            })
          }
        } else {
          return false
        }
      })
    },
    // 图片上传模块
    imageChoose(img) {
      this.form.cover = img
      this.$refs.form.validateField('cover')
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleDelete(id) {
      this.$confirm('是否删除该课程?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'danger'
      }).then(() => {
        courseApi.deleteItem({ id: id }).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.fetchData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.video-list {
  .screen-box {
    .screen-item {
      text-align: right;
    }
    .operation {
      display: block;
      text-align: right;
    }
  }
  .cover {
    display: inline-block;
    vertical-align: middle;
  }
}
</style>

<style lang="scss">
